from django.shortcuts import render
from .models import Blog
from teachzero import settings
import time

# Create your views here.

from home.views import user_check


def index(request):
    """返回首页"""
    context = user_check(request)
    blogs = Blog.objects.all()
    blogs = sorted(blogs, key=lambda x: (x.modified_time, x.id))
    context["blogs"] = blogs[::-1]
    return render(request, "blog/index.html", context)


def blog_detail(request, url):
    """根据md5获取博客"""
    context = user_check(request)
    blog = Blog.objects.filter(md5=url)
    if blog:
        blog = blog[0]
        context["title"] = f"{settings.TITLE}-{blog.name}"
        context["url"] = blog.url + f"?t={time.time()}"
        if blog.url.endswith(".pdf"):
            context["ispdf"]=True
    else:
        context["message_danger"] = "查无此博客"
    return render(request, "blog/item.html", context)


def update_log(request):
    """获取更新日志"""
    context = user_check(request)
    blog = Blog.objects.filter(name="更新日志")
    if blog:
        blog = blog[0]
        context["url"] = blog.url + f"?t={time.time()}"
    else:
        context["message_danger"] = "暂无更新日志"
    return render(request, "blog/item.html", context)
